import React from "react";
import {Select, Card, Form, Input, Button, message, Icon, Checkbox} from "antd";
import axios from '../../components/Engineering/axios';

const FormItem = Form.Item;
const {Option} = Select;

class FormLogin1 extends React.Component {
  state = {}

  componentWillMount() {
    axios.ajax({url: '/mock/demo/data',}).then((res) => {
      let {data} = res
      data.sex = {"1": "男", "2": "女"}[data.sex]
      this.props.form.setFieldsValue(res.data)
    })
  }

  handleSubmit = () => {
    let userInfo = this.props.form.getFieldsValue();   //todo kim-stamp获取双向绑定的值
    this.props.form.validateFields((err, values) => {  //todo kim-stamp 验证字段
      if (!err) {
        message.success(
          `${userInfo.userName} 恭喜你，您通过本次表单组件学习，当前密码为：${
            userInfo.password
            }`
        );
        console.log(values)
      }
    });
  };

  render() {
    const {getFieldDecorator, getFieldsValue, validateFields} = this.props.form;
    const {test1, test2} = this.state;
    console.error(this.props)

    const formItemLayout = {
      labelCol: {
        xs: {span: 8},
        sm: {span: 6}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      }
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 20,
          offset: 4
        }
      }
    };


    return (
      < div>

        <Card title="设置数据" style={{marginTop: 10}}>
          <Form layout="inline">
            <FormItem label="用户名" colon={false} hasFeedback validateStatus="success" help="请在这里输入账号...">
              {getFieldDecorator("username", {
                initialValue: "",

              })(<Input placeholder="请输入用户名"/>)}
            </FormItem>

            <FormItem label="性别" colon={false}>
              {getFieldDecorator("sex", {
                initialValue: "",
              })(<Input placeholder="请输入密码"/>)}
            </FormItem>


            <FormItem label="性别" colon={false}>
              {getFieldDecorator("thirdName", {
                initialValue: "",
              })(
                <Select
                  placeholder="Select a person"
                  style={{width: 200}}
                  // onChange={onChange}
                  // onFocus={onFocus}
                  // onBlur={onBlur}
                  // onSearch={onSearch}
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {
                    [
                      {value: "jack", name: "杰克"},
                      {value: "lucy", name: "露西"},
                      {value: "tom", name: "汤姆"},
                      {value: "kim", name: "清风"},
                    ].map(item => <Option key={item.value}
                                          Rvalue={item.value}>{item.name}</Option>)
                  }
                </Select>
              )}
            </FormItem>


          </Form>
        </Card>


        <Card title="登录行内表单" style={{marginTop: 10}}>
          <Form layout="inline">
            {/* //todo validateStatus: 校验状态，可选 'success', 'warning', 'error', 'validating'。
          hasFeedback：用于给输入框添加反馈图标。
          help：设置校验文案。 */}
            <FormItem label="用户名" validateStatus="success" hasFeedback help="请在这里输入账号...">
              {getFieldDecorator("userName", {
                initialValue: "",
                rules: [
                  {
                    required: true,
                    message: "用户名不能为空"
                  }
                ]
              })(<Input placeholder="请输入用户名"/>)}
            </FormItem>

            <FormItem label="密码">
              {getFieldDecorator("password", {
                initialValue: "",
                rules: [
                  {
                    required: true,
                    message: "密码不能为空"
                  }
                ]
              })(<Input placeholder="请输入密码"/>)}
            </FormItem>
            <FormItem>
              <Button type="primary" onClick={this.handleSubmit}>登录</Button>
            </FormItem>
          </Form>
        </Card>

      </div>
    );
  }
}


class FormLogin2 extends React.Component {

  handleSubmit = () => {
    let userInfo = this.props.form.getFieldsValue();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        message.success(
          `${userInfo.userName} 恭喜你，您通过本次表单组件学习，当前密码为：${
            userInfo.password
            }`
        );
        console.log(values)
      }
    });
  };

  handleComparToFirstPassword = (rule, value, callback) => {
    const form = this.props.form;
    value && value !== form.getFieldValue("password") ? callback("您输入的两个密码不一致！") : callback(<div
      style={{color: "green"}}><Icon type="check-circle"/> 密码正确,请点击注册</div>)
  };


  render() {
    const {getFieldDecorator} = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 18}
      }
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 20,
          offset: 4
        }
      }
    };

    return (
      <div>
        <Card title="登录水平表单" style={{marginTop: 10}}>
          {/* //todo kim-doc  layout 表单布局 horizontal(水平)|vertical(垂直)|inline(行内)
                                             hideRequiredMark	隐藏所有表单项的必选标记
                                             labelAlign	label   标签的文本对齐方式   'left' | 'right'
                                             */}
          <Form style={{width: 600}} {...formItemLayout} layout="horizontal" labelAlign="left">
            <FormItem label="用户名">
              {getFieldDecorator("username", {
                initialValue: "",
                validateFirst: true,   //todo 当某一规则校验不通过时，是否停止剩下的规则的校验
                rules: [
                  {
                    required: true,
                    message: "用户名不能为空"
                  },
                  {
                    min: 2,
                    max: 8,
                    message: "长度不在范围内"
                  },
                ]
              })(
                <Input
                  prefix={<Icon type="user"/>}
                  placeholder="请输入用户名"
                />
              )}
            </FormItem>

            <FormItem label="密码">
              {getFieldDecorator("password", {
                initialValue: "",
                validateFirst: true,   //todo kim-doc 当某一规则校验不通过时，是否停止剩下的规则的校验
                rules: [
                  {
                    required: true,
                    message: "密码不能为空"
                  },
                  {
                    whitespace: true,
                    message: "开头密码不为空"
                  },
                  {
                    min: 6,
                    max: 16,
                    message: "长度不在范围内"
                  },
                ]
              })(
                <Input.Password
                  prefix={<Icon type="lock"/>}
                  type="password"
                  placeholder="请输入密码"
                />
              )}
            </FormItem>

            <FormItem label="再次输入密码">
              {getFieldDecorator("password2", {
                initialValue: "",
                validateFirst: true,   //当某一规则校验不通过时，是否停止剩下的规则的校验
                rules: [
                  //todo kim-doc 校验规则
                  // type	内建校验类型，可选项	string	'string'	  eg:'email'
                  // enum	枚举类型	string	-
                  // len	字段长度	number	-
                  // min	最小长度	number	-
                  // max	最大长度	number	-
                  // pattern	正则表达式校验	RegExp	-
                  // required	是否必选	boolean	false
                  // transform	校验前转换字段值	function(value) => transformedValue:any	-
                  // validator	自定义校验（注意，callback 必须被调用）	function(rule, value, callback)	-
                  // whitespace	必选时，空格是否会被视为错误	boolean	false
                  // message	校验文案	string|ReactNode	-
                  {
                    required: true,
                    message: "密码不能为空"
                  },
                  {
                    whitespace: true,
                    message: "密码不可以开头"
                  },
                  {
                    min: 6,
                    max: 16,
                    message: "长度不在范围内"
                  },
                  {
                    pattern: /^\w+$/g,
                    message: '密码必须为字母或者数字'
                  },
                  // {
                  //   pattern: new RegExp("^\\w+$", "g"),
                  //   message: "密码必须为字母或者数字"
                  // },

                  {
                    validator: this.handleComparToFirstPassword //todo kim-doc 自定义校验规则
                  },
                ]
              })(
                <Input.Password
                  prefix={<Icon type="lock"/>}
                  type="password"
                  placeholder="请输入密码"
                  hasFeedback
                />
              )}
            </FormItem>

            <FormItem label="" {...tailFormItemLayout}>
              {getFieldDecorator("remember", {
                valuePropName: "checked",
                initialValue: true
              })(<Checkbox>记住密码</Checkbox>)}
              <a href="#" style={{float: "right"}}>
                忘记密码
              </a>
            </FormItem>

            <FormItem label="" {...tailFormItemLayout}>
              <Button
                type="primary"
                onClick={this.handleSubmit}
                style={{width: "100%"}}
              >
                登录
              </Button>
            </FormItem>
          </Form>
        </Card>
      </div>
    );
  }
}


//todo kim-doc Form.create(options) 使用 class CustomizedForm extends React.Component {} CustomizedForm = Form.create({})(CustomizedForm);
// options 的配置项如下
// name	               设置表单域内字段 id 的前缀
// validateMessages	   默认校验信息，可用于把默认错误信息改为中文等，格式与 newMessages 返回值一致
// onValuesChange	   任一表单域的值发生改变时的回调    (props, changedValues, allValues) => void
// onFieldsChange	   当 Form.Item 子节点的值（包括 error）发生改变时触发，可以把对应的值转存到 Redux store	Function(props, changedFields, allFields)
// mapPropsToFields	   把父组件的属性映射到表单项上（如：把 Redux store 中的值读出），需要对返回值中的表单域数据用 Form.createFormField 标记，注意表单项将变成受控组件, error 等也需要一并手动传入     (props) => ({ [fieldName]: FormField { value } })


// 经过 Form.create 之后如果要拿到 ref，可以使用 rc-form 提供的 wrappedComponentRefclass CustomizedForm extends React.Component { ... }

// use wrappedComponentRef
// const EnhancedForm =  Form.create()(CustomizedForm);
// <EnhancedForm wrappedComponentRef={(form) => this.form = form} />
// this.form // => The instance of CustomizedForm

const WrappedRegistrationForm1 = Form.create({name: 'FormLogin1'})(FormLogin1)
const WrappedRegistrationForm2 = Form.create({name: 'FormLogin2'})(FormLogin2);

//无状态函数 不是这样写的不可以这样，这只是一个变量
// const Login = (
//   <div>
//     <WrappedRegistrationForm1 />
//     <WrappedRegistrationForm2 />
//   </div>
// )

//无状态函数写法1，或者可以加参数作为来接受父组件的值const Login = (props) => (<div>{props.name}</div>)
// const Login = (porps) => {
//   const a = 1;
//   return (
//     <div>
//       <WrappedRegistrationForm1 />
//       <WrappedRegistrationForm2 />
//     </div>
//   )
// }
// export default Login;


//无状态函数写法2
// function Login (porps) {
//   return (
//     <div>
//       <WrappedRegistrationForm1 />
//       <WrappedRegistrationForm2 />
//     </div>
//   )
// }
// export default Login;

//无状态函数写法3
export default porps => <> <WrappedRegistrationForm1/> <WrappedRegistrationForm2/> </>
